<template>
<el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
  <el-form-item label="账号" prop="username">
    <el-input v-model="ruleForm.username"></el-input>
  </el-form-item>

  <el-form-item label="密码" prop="password">
    <el-input v-model="ruleForm.password" type="password"></el-input>
  </el-form-item>
  <el-form-item>
    <el-button type="primary" @click="submitForm()">登录</el-button>
    <el-button @click="resetForm()">重置</el-button>
  </el-form-item>
</el-form>
</template>

<script>
import service from 'utils/request'

export default {
  data() {
    return {
      ruleForm: {
        username: '',
        password: '',
      },
      rules: {
        username: [
          { required: true, message: '请输入账号', trigger: 'blur' },
          { min: 3, max: 30, message: '长度在 3 到 30 个字符', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 5, max: 30, message: '长度在 3 到 30 个字符', trigger: 'blur' }
        ],
      }
    }
  },
  methods: {
    submitForm(formName) {
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          this._login()
        } else {
          this.$message.error('表单验证失败')
          return false
        }
      })
    },

    _login() {
      const {
        username,
        password,
      } = this.ruleForm
      service.post('/login', {
        username,
        password,
      }).then(res => {
        this._loginSuccess(res)
      }).catch(_ => {
        console.log('接口请求失败了')
      })
    },

    _loginSuccess(res) {
      const {
        token,
        userInfo,
      } = res
      this.$store.commit('SET_TOKEN', token)
      this.$store.commit('SET_USER_INFO', userInfo)
      this.$router.replace('/')
    },

    resetForm(formName) {
      this.$refs.ruleForm.resetFields()
    }
  }
}
</script>

<style>

</style>
